// pages/my/user-edit/index.js
const App = getApp();
const baseUrl = require("../../../api/config").dev; //这里用的是ES6的写法
const WXAPI = require("../../../api/api");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sPhone:'',
    headImg:'',
    headImg2:'',
    nickname:'',
    sSignature:"",
    isSubmit: false,
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      avatarUrl,
    });
    let _this = this;
    wx.getFileSystemManager().readFile({
      filePath: avatarUrl,
      encoding: "base64",
      success: (res) => {
        console.log("res", res);
        _this.setData({
          headImg: `data:image/png;base64,${res.data}`,
          headImg2: `data:image/png;base64,${res.data}`,
        });
      },
    });
  },
  async saveMyInfo() {
    this.setData({
      isSubmit: true,
    });
    if (!this.data.headImg) {
      wx.showToast({
        title: "请上传头像！",
      });
      return;
    }
    if (!this.data.nickname) {
      return;
    }
    let params = {
      sHeadimgBase64: this.data.headImg2,
      sNickname: this.data.nickname,
      sSignature: this.data.sSignature,
      sPhone: this.data.sPhone
    };
    let res = await WXAPI.editUserInfo(params);
    if (res.data.code == 0) {
      wx.showToast({
        title: res.data.message,
      });
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        });
        var page = getCurrentPages();
        var prevPage = page[page.length - 2];
        // 返回刷新
        prevPage.getUserInfo()
        // if (prevPage == undefined || prevPage == null) return;
        // prevPage.onLoad();
      }, 2000);
    }
    this.setData({
      isSubmit: false,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.userInfo) {
      this.setData({
        headImg: `${baseUrl["baseUrl"]}/files/${JSON.parse(options.userInfo).sHeadimgurl}`,
        nickname: JSON.parse(options.userInfo).sNickname,
        sSignature: JSON.parse(options.userInfo).sSignature,
        sPhone: JSON.parse(options.userInfo).sPhone,
      });
    } 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
